package com.wngbms.netty._02http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        Channel channel = ctx.channel();
        System.out.println(channel);
        ChannelPipeline pipeline = ctx.pipeline();
        System.out.println(pipeline);
        Channel channel1 = pipeline.channel();
        System.out.println(channel1);

        ChannelHandler handler = ctx.handler();
        System.out.println(handler);

        if (msg instanceof HttpRequest) {

            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.getUri());

            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("favicon");
                return;
            }

            ByteBuf byteBuf = Unpooled.copiedBuffer("hello.server", CharsetUtil.UTF_8);

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

            ctx.writeAndFlush(response);
        }
    }
}
